package com.qsl.ssyx.product.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.qsl.ssyx.product.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
@Service
public class fileUploadServiceImpl implements FileUploadService {

    //   阿里云-对象存储(OSS)     地域，存储桶名，秘钥（secretId，secretKey）
    @Value("${aliyun.oss.endpoint}")
    String endpoint;
    @Value("${aliyun.oss.bucketName}")
    String bucketName;
    @Value("${aliyun.oss.accessKeyID}")
    String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    String accessKeySecret;

    @Override
    public String fileUpload(MultipartFile file) {
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename(); // 获取文件名称
            //生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;
            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //  2021/02/02/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl + "/" + fileName;
// 文件流
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
//            PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, inputStream);
            putObjectRequest.setProcess("true"); //设置该属性可以返回response。 不设置，response返回空

            // 创建 PutObjectResult请求
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            //上传之后文件路径
            // https://ssyx-qsl.oss-cn-guanzhou.aliyuncs.com/01.jpg
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            System.out.println("==状态=>" + result.getResponse().getStatusCode());
            System.out.println("=报错信息==>" + result.getResponse().getErrorResponseAsString());
            System.out.println("==路径=>" + result.getResponse().getUri());
            System.out.println("==路径2=>" + url);
            //返回
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
